package com.iye.puretennis.helper;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import com.iye.puretennis.domain.User;
import com.iye.puretennis.domain.UserToken;

/**
 * Author: Chuanbao on 2014/11/12.
 */
public class DBManager {
    private DBHelper helper;
    private SQLiteDatabase db;

    public DBManager(Context context) {
        helper = new DBHelper(context);
        db = helper.getWritableDatabase();
    }

    /**
     * after login the app,some data need to be stored
     * @param guid the guid of the user
     * @param token the access token to remote server
     */
    public void login(String guid,String token){
        db.execSQL("insert into "+DBHelper.TABLE_USER_TOKEN+" values(null,?,?)",new Object[]{guid,token});
    }

    /**
     * logout and remove the login data
     */
    public void logout(){
        db.execSQL("delete from usertoken");
    }

    public UserToken retrieveCurrentUser(){
        Cursor cursor = db.rawQuery("select guid,token from usertoken",new String[]{});
        if(cursor.moveToFirst()){
            String guid = cursor.getString(0);
            String token = cursor.getString(1);
            return new UserToken(guid,token);
        }
        return null;
    }

    /**
     * retrieve user by token
     * @param token the access token to remote server
     * @return
     */
    public User retrieveUser(String token){
        Cursor cursor = db.rawQuery("select guid,token from user where token=?", new String[]{token});
        if(cursor.moveToFirst()){
            String guid = cursor.getString(0);
            return new User(guid,token);
        }
        return new User();
    }

    public void addIdols(String idolsJson){
        db.execSQL("insert into "+DBHelper.TABLE_USER+" values(null,?)",new Object[]{idolsJson});
    }

    public void cacheMyData(String jsonStr,String cacheType){
        String guid = retrieveCurrentUser().getGuid();
        db.execSQL("insert into "+DBHelper.TABLE_MYCACHES+" values(null,?,?,?)",new Object[]{guid,cacheType,jsonStr});
    }

    public String retrieveMyCachedData(String cacheType){
        String guid = retrieveCurrentUser().getGuid();
        Cursor cursor = db.rawQuery("select content from mycaches where userguid=? and cachetype=?", new String[]{guid, cacheType});
        if(cursor.moveToFirst()){
            return cursor.getString(0);
        }
        return null;
    }

    public void updateMyCachedData(String cacheType, String jsonStr) {
        String guid = retrieveCurrentUser().getGuid();
        ContentValues columns = new ContentValues();
        columns.put("content",jsonStr);
        db.update("mycaches",columns,"userguid=? and cachetype=?",new String[]{guid,cacheType});
    }
}
